package com.huilian.iotbox.data.service.impl;
import com.huilian.iotbox.data.dao.PushConfigCommonDao;
import com.huilian.iotbox.data.po.PushConfigTemplate;
import com.huilian.iotbox.data.po.User;
import com.huilian.iotbox.data.service.PushConfigCommonService;
import com.huilian.iotbox.data.service.PushConfigTemplateCommonService;
import com.huilian.iotbox.data.service.UserCommonService;
import com.huilian.iotbox.data.vo.PushConfigVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


@Service
public class PushConfigCommonServiceImpl implements PushConfigCommonService {


    @Autowired
    private UserCommonService userCommonService;
    @Autowired
    private PushConfigCommonDao pushConfigCommonDao;
    @Autowired
    private PushConfigTemplateCommonService pushConfigTemplateCommonService;

    /**
     *  用户存在情况下 查询通知配置表
     *      1，没查询到该用户通知配置数据则默认开启
     *      2，查询到了就按数据IsOpen开关 来
     */
    @Override
    public PushConfigVo findOpenOrNotByUserId(Integer userId, Integer type) {
        final User user = userCommonService.getOfficialAccountOpenId(userId);
        if (StringUtils.isEmpty(user) || StringUtils.isEmpty(user.getOfficialAccountOpenId())){
            return null;
        }
        Integer appletOrOfficialType = 1;
        PushConfigVo pushConfigVo = pushConfigCommonDao.findOpenOrNotByUserId(userId, type,appletOrOfficialType);
        if (!StringUtils.isEmpty(pushConfigVo)) {
            // 情况2
            if (!pushConfigVo.getIsOpen()) {
                // 情况2，关闭了通知
                return null;
            }
        } else {
            // 情况1
            pushConfigVo = pushConfigCommonDao.findType(type);
        }
        pushConfigVo.setOfficialAccountOpenId(user.getOfficialAccountOpenId());

        PushConfigTemplate condition = new PushConfigTemplate();
        condition.setPushConfigId(pushConfigVo.getId());
        if (StringUtils.isEmpty(user.getOfficialAccountId())){
            condition.setIsDefault(true);
        } else {
            condition.setAppletOrOfficialAccountId(user.getOfficialAccountId());
            pushConfigVo.setAppletOrOfficialAccountId(user.getOfficialAccountId());
        }
        final PushConfigTemplate pushConfigTemplate = pushConfigTemplateCommonService.findOneByCondition(condition);
        pushConfigVo.setTemplateId(pushConfigTemplate.getTemplateId());
        return pushConfigVo;
    }
}
